package com.rede.didiok.rank.security.service;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.TypeReference;
import com.rede.didiok.common.constant.conf.RedisConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.dto.user.UserDto;
import com.rede.didiok.common.enums.StatusEnum;
import com.rede.didiok.common.exception.exceptionType.FeignException;
import com.rede.didiok.common.feign.UserFeignClient;
import com.rede.didiok.common.utils.JsonUtils;
import com.rede.didiok.common.utils.R;
import com.rede.didiok.common.utils.RedisUtil;
import com.rede.didiok.common.utils.StringUtils;
import com.rede.didiok.rank.security.SecurityUserFactory;
import com.rede.didiok.rank.security.exception.UserNonactivatedException;

/**
 * 将SpringSecurity中的用户管理和数据库的管理员对应起来
 *
 */
@Service
@Slf4j
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    private RedisUtil redisUtil;

    /**
     * @param username 浏览器输入的用户名【需要保证用户名的唯一性】
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从 redis中获取用户信息
        String userJson = redisUtil.get(RedisConf.USER_INFO_BY_USER_NAME + Constants.SYMBOL_COLON + username);
        UserDto user;
        if (StringUtils.isNotEmpty(userJson)) {
            user = JsonUtils.jsonToPojo(userJson, UserDto.class);
        }else {
            // 根据用户名获取用户信息
            R result = userFeignClient.getByUserName(username);
            if(result.getCode()==0){
                user = result.getData(new TypeReference<UserDto>(){});
                // TODO 这里只有存储，但是没有写删除
                redisUtil.setEx(RedisConf.USER_INFO_BY_USER_NAME + Constants.SYMBOL_COLON + username, JsonUtils.objectToJson(user), 2, TimeUnit.HOURS);
            }else {
                // 获取异常信息
                String msg = result.getData("msg",new TypeReference<String>(){});
                throw new FeignException("feign调用异常（根据用户名获取用户信息）："+msg);
            }
        }

        if (user == null || StatusEnum.DISABLED == user.getStatus()) {
            log.error(String.format("[%s]该账号未注册,无法登录", username));
            throw new UsernameNotFoundException(String.format("[%s]该账号未注册,无法登录", username));
        } else {
            if (StatusEnum.FREEZE == user.getStatus()) {
                log.error(String.format("[%s]该账号未激活,无法登录", username));
                throw new UserNonactivatedException(String.format("[%s]该账号未激活,无法登录", username));
            }
            return SecurityUserFactory.create(user, "web");
        }
    }
}
